package com.central.apps.handler.contract;

import cn.hutool.core.map.MapUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.central.app.common.util.DateUtils;
import com.central.app.entity.TBFile;
import com.central.app.service.CheckConNodeService;
import com.central.app.service.HandlerService;
import com.central.apps.handler.base.LvBaseHandler;
import com.central.apps.handler.until.DateUtiles;
import com.central.bizcommon.model.flow.FlowNode;
import com.central.bizcommon.model.flow.FlowOpinion;
import com.central.common.exception.service.ServiceException;
import com.central.common.util.ToolUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2022/9/22.
 */
@Slf4j
@Component
public class ConsignsHandler extends LvBaseHandler {
    @Autowired
    private HandlerService handlerService;
    @Autowired
    private FileSynUtilService fileSynUtilService;
    @Autowired
    private ConchangeHandler conchangeHandler;
    @Autowired
    private ConUtil conUtil;
    @Resource
    private CheckConNodeService checkConNodeService;
    @Override
    public void beforDelete(String app, String objName, Long id, boolean isLogic) {
        // 更新采购订单标记
        handlerService.updateBySql("update gq_po set converttocon = '0' where ponum in (select ponum from gq_consigns where id = " + id + ")");
    }

    //    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
//        if("gq_consigns".equals(objName)&&!isUpdate){
//            String concode = MapUtils.getString(data,"concode");
//            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_consigns where concode = '"+concode+"'");
//            if (CollectionUtils.isNotEmpty(list)) {
//                throw new ServiceException("合同编号已存在，请修改合同编号") ;
//            }
//        }
//    }
    @Override
    public void beforSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        if ("gq_consigns".equals(objName) && !isUpdate) {
            String concode = MapUtils.getString(data, "concode");
            List<Map<String, Object>> list = handlerService.findBySql("select id from gq_consigns where concode = '" + concode + "'");
            if (CollectionUtils.isNotEmpty(list)) {
                throw new ServiceException("合同编号已存在，请修改合同编号");
            }
        }
        if ("gq_consigns".equals(objName)){
        //获取合同节点最小时间和最大时间，跟合同时间进行判断
            List<Map<String,Object>> list1 = handlerService.findBySql("select starttime from gq_connode where starttime is not null and cid = "+data.get("id")+"  order by starttime asc limit 1");
            if(CollectionUtils.isNotEmpty(list1)){
                Date nodeStart = DateUtils.getDate(MapUtils.getString(list1.get(0),"starttime")) ;//节点最小时间
                Date startime = DateUtils.getDate(MapUtils.getString(data,"starttime")) ;
                if(startime.getTime()>nodeStart.getTime()){
                    throw new ServiceException("合同开始日期必须小于所有节点的开始日期");
                }
            }
            List<Map<String,Object>> list2 = handlerService.findBySql("select endtime from gq_connode where endtime is not null and cid = "+data.get("id")+"  order by endtime desc limit 1");
            if(CollectionUtils.isNotEmpty(list2)){
                Date nodeEnd = DateUtils.getDate(MapUtils.getString(list2.get(0),"endtime")) ;
                Date endtime = DateUtils.getDate(MapUtils.getString(data,"endtime")) ;
                if(endtime.getTime()<nodeEnd.getTime()){
                    throw new ServiceException("合同结束日期必须大于所有节点的结束日期");
                }
            }
        }
    }
    @Override
    public void afterSave(String app, String objName, Map<String, Object> data, boolean isUpdate) throws Exception {
        //保存后，将合同申请或者合同评审中的合同文本添加到合同签订位置
        if("gq_consigns".equals(objName)&&!isUpdate&&!"绵阳".equals(data.get("signingplace"))){
            int conid = MapUtils.getIntValue(data,"conid");
            String appname="conaccountApp";
            Long id = MapUtil.getLong(data, "id");
            String conname = MapUtils.getString(data,"conname");
            conUtil.moveFile(conid,appname,app,id,conname);
        }
        if("gq_consigns".equals(objName)&&!isUpdate&&"绵阳".equals(data.get("signingplace"))){
            Map<String, Object> conapplicationMap = new HashMap<>();
            handlerService.addBizNum("conapplicationApp", "gq_conapplication", conapplicationMap);
            Map<String,Object> map = new HashMap<>();
            map.put("conid","1001"+MapUtils.getString(conapplicationMap, "conid"));
            map.put("id",data.get("id"));
            handlerService.update("gq_consigns",map);
        }
        if("gq_consigns".equals(objName)&&!isUpdate){
            //保存后，给子表文件列表自动赋值
            conUtil.setlistfile(MapUtils.getIntValue(data,"id"),app,MapUtils.getIntValue(data,"conid"));
        }

    }
//    public void setlistfile(int id,String appname,int conid) throws Exception {
//        List<Map<String, Object>> list = handlerService.findBySql("select paramname from gq_pcline where paramcode ='"+appname+"'");
//        if(CollectionUtils.isNotEmpty(list)){
//            for (Map<String, Object> stringObjectMap : list) {
//                Map<String,Object> map = new HashMap<>();
//                map.put("pid",id);
//                map.put("conid",conid);
//                map.put("appname",appname);
//                map.put("status","未上传");
//                map.put("taskdelname",stringObjectMap.get("paramname"));
//                handlerService.insert("gq_filelist",map);
//            }
//
//        }
//    }
//    @Override
//    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {
//
//        System.out.println("=============合同申请审批前，进入代码==============================flowNode.getId() =========" + flowNode.getId());
//        //最后一步，审批前，验证合同编号，合同印章是否已填写完毕
//        if (flowNode.getId().equals("approvalthree")) {
//            String sql = "select * from  gq_consigns where id = " + id;
//            List<Map<String, Object>> list = handlerService.findBySql(sql);
//            if (CollectionUtils.isNotEmpty(list)) {
//
//                if (list.get(0).get("concode") == null || "".equals(list.get(0).get("concode"))) {
//                    String res = "合同编号未填写，请填写后在进行审批";
//                    return res;
//                }
//                if (!"已完成".equals(list.get(0).get("ourcomplete"))) {
//                    String res = "请上传甲方印章文件，在进行审批";
//                    return res;
//                }
//                if (!"已完成".equals(list.get(0).get("oppcomplete"))) {
//                    String res = "请上传乙方盖章文件，在进行审批";
//                    return res;
//                }
//
//            }
//
//        }
//        return super.beforeExcuteFlow(app, id, flowNode, op);
//    }


    @Override
    public void afterExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op, String event) throws Exception {


    }

    @Override
    public String beforeExcuteFlow(String app, Long id, FlowNode flowNode, FlowOpinion op) throws Exception {

        //流程提交前，判断收付款节点金额之和是否等于合同金额
        String sql9 = "select totalprice,concode,isframecon,ponum from  gq_consigns where id = " + id;
        List<Map<String, Object>> list9 = handlerService.findBySql(sql9);
        if (flowNode.getId().equals("submit")) {
            if (CollectionUtils.isNotEmpty(list9)) {
                String sql2 = "select sum(receivingamounttax) as receivingamounttaxs from  gq_connode where concode = '" + list9.get(0).get("concode")+"' and ispaynode ='是'";
                List<Map<String, Object>> list2 = handlerService.findBySql(sql2);
                if (CollectionUtils.isNotEmpty(list2)&&list2!=null&&list2.size()>0) {
                    boolean isfra = true;//是否进行节点金额和合同金额的验证
                    String isframecon = MapUtils.getString(list9.get(0),"isframecon");//是否是框架合同
                    String ponum = MapUtils.getString(list9.get(0),"ponum");
                    //框架合同不需要节点数据，因此也不需要进行验证
                    if(ToolUtil.isEmpty(isframecon)||"是".equals(isframecon)){
                        isfra = false;
                    }
                    //采购订单生成的合同，不需要进行金额和节点的验证,因为采购订单生成的合同不需要付款节点，它从采购那边进行付款
                    if(ToolUtil.isNotEmpty(ponum)){
                        isfra = false;
                    }

                    if(isfra){
                        BigDecimal totalprice = new BigDecimal(MapUtils.getString(list9.get(0),"totalprice"));
                        if(ToolUtil.isEmpty(MapUtils.getString(list2.get(0),"receivingamounttaxs"))){
                            return "请添加非工作节点信息，并且节点金额之和要等于合同金额";
                        }
                        BigDecimal receivingamounttaxs = new BigDecimal(MapUtils.getString(list2.get(0),"receivingamounttaxs"));
                        if(totalprice.compareTo(receivingamounttaxs)!=0){
                            return "合同节点金额之和与合同金额不等，请修改合同节点金额";
                        }
                    }
                    List<TBFile> tbFiles = checkConNodeService.selectFiles(app, id );
                    if (CollectionUtils.isEmpty(tbFiles)||tbFiles==null) {
                        return "需要上传合同文件，再提交流程";
                    }
                }
            }

        }

        //System.out.println("流程审批后，进入代码==============================flowNode.getId() =========" + flowNode.getId());
        //-----------------------------------------------流程审批后-------------------------------
        if (flowNode.getId().equals("approval")) {
            boolean flag = op.isFlag();
            if (flag) {
                String sql = "select * from  gq_consigns where id = " + id;
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                if (CollectionUtils.isNotEmpty(list)) {
                    String ispublicity = (String) list.get(0).get("ispublicity");//是否公示
                    if ("是".equals(ispublicity)) {
                        //conchangeHandler.updateStatus((String) list.get(0).get("concode"), "公示中");
                        conchangeHandler.updateStatusByid(id, "公示中");
                        //设置公示结束时间 ,公示期中的签订页面不许修改，只能查看
                        int publicity = (int) list.get(0).get("publicity");
                        Date publicityend = DateUtiles.stepDay(new Date(), publicity);
                        Map<String, Object> map = new HashMap<>();
                        map.put("id", id);
                        map.put("publicityend", publicityend);
                        handlerService.update("gq_consigns", map);
                    } else {
                        //conchangeHandler.updateStatus((String) list.get(0).get("concode"), "已批准");
                        conchangeHandler.updateStatusByid(id, "已批准");
                    }
                }
            }
        }

        //提交审批后，状态更改成审批中
        if (flowNode.getId().equals("submit")) {
            boolean flag = op.isFlag();
            if (flag) {
                String sql = "select * from  gq_consigns where id = " + id;
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                if (CollectionUtils.isNotEmpty(list)) {
                    //conchangeHandler.updateStatus((String) list.get(0).get("concode"), "审批中");
                    conchangeHandler.updateStatusByid(id, "审批中");
                }
            }
        }
        /*
         * 合同签订审批通过后，插入到合同台账数据
         * */
        if (flowNode.getId().equals("approval")) {
            boolean flag = op.isFlag();
            if (flag) {
                String sql = "select * from  gq_consigns where id = " + id;
                List<Map<String, Object>> list = handlerService.findBySql(sql);
                if (CollectionUtils.isNotEmpty(list)) {
                    for (Map<String, Object> objectMap : list) {
                        int conid = MapUtils.getIntValue(objectMap, "conid");
                        String concode = MapUtils.getString(objectMap, "concode");
                        String conname= MapUtils.getString(objectMap, "conname");
//                        try {
//                            //获取采购订单号，如果不为空，赋值合同名称和合同编号
//                            String ponum = MapUtils.getString(list.get(0),"ponum");
//                            if(ToolUtil.isNotEmpty(ponum)){
//                                handlerService.updateBySql("update gq_po set concode = '"+concode+"' , conname = '"+conname+"' where ponum = '"+ponum+"'");
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                        //将合同编号更细到合同申请和合同评审中去
                        try {
                            handlerService.updateBySql("update gq_conapplication set concode = '" + concode + "',constatus = '已签订' where conid = " + conid);
                            handlerService.updateBySql("update gq_conreviews set concode = '" + concode + "' ,constatus = '已签订' where conid = " + conid);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        //通过插入合同台账
                        //查询收付款节点个数，赋值到台账，台账卡片所需要的值
                        String surplusnode = "0";
                        String sql5 = "select * from gq_connode where concode = '" + objectMap.get("concode") + "' and ispaynode ='是'";
                        List<Map<String, Object>> list5 = handlerService.findBySql(sql5);
                        if (CollectionUtils.isNotEmpty(list5)) {
                            surplusnode = list5.size() + "";
                        }
                        //关联合同个数
                        String relationnum = "0";
                        if (objectMap.get("relationname") != null && !"".equals(objectMap.get("relationname"))) {
                            relationnum = "1";
                        }
                        Map<String, Object> map = new HashMap<>();
                        //绵阳合同 的话，查询台账数据为空
                        List<Map<String, Object>> list6 = handlerService.findBySql("select id from gq_conaccount where conid = '" + objectMap.get("conid") + "'");
                        if(CollectionUtils.isNotEmpty(list6)){
                            map.put("id", list6.get(0).get("id"));
                        }
                        map.put("concode", objectMap.get("concode"));//合同编号
                        map.put("conname", objectMap.get("conname"));//合同名称
                        map.put("totalprice", objectMap.get("totalprice"));//合同金额（含税）
                        map.put("nototalprice", objectMap.get("nototalprice"));//合同金额（不含税）
                        map.put("condept", objectMap.get("condept"));//合同责任部门
                        map.put("conuser", objectMap.get("createuserdesc"));//合同经办人
                        map.put("closttime", objectMap.get(""));//关闭时间 合同关闭时，需要走一个流程，走完流程后，赋值合同关闭时间
                        map.put("taketime", objectMap.get("starttime"));//生效时间
                        //map.put("oppcompany", objectMap.get("oppcompany"));//合同对方单位
                        //map.put("constatus", objectMap.get("constatus"));//合同状态
                        map.put("constatus", "已签订");//合同状态
                        map.put("conterm", objectMap.get("endtime"));//合同期限
                        map.put("maincon", objectMap.get("maincon"));//关联合同编号
                        map.put("contracttype", objectMap.get("contracttype"));//合同类型
                        map.put("isframecon", objectMap.get("isframecon"));//是否为框架合同
                        map.put("isadcharge", objectMap.get("isadcharge"));//是否预付款
                        map.put("relationprocode", objectMap.get("relationprocode"));//关联项目编号
                        map.put("createuserdesc", objectMap.get("createuserdesc"));//创建人
                        map.put("status", "已签订");//审批状态
                        //map.put("relationproname", objectMap.get("relationprocodeEntity_proname"));//关联项目名称
                        map.put("relationname", objectMap.get("relationname"));//关联合同名称
                        map.put("starttime", objectMap.get("starttime"));//合同开始时间
                        map.put("endtime", objectMap.get("endtime"));//合同结束时间
                        map.put("purchasenum", objectMap.get("purchasenum"));//采购预订单
                        map.put("contemplate", objectMap.get("contemplate"));//合同模板
                        map.put("contemplatename", objectMap.get("contemplatename"));//合同模板名称
                        map.put("oppcompany", objectMap.get("oppcompany"));//对方单位名称
                        map.put("surplusnode", surplusnode);//剩余收付款节点个数
                        map.put("relationnum", relationnum);//关联合同数
                        map.put("cosid", objectMap.get("cosid"));//项目成本主键
                        map.put("proid", objectMap.get("proid"));//项目主键
                        map.put("taskid", objectMap.get("taskid"));//任务主键
                        map.put("qid", objectMap.get("id"));//合同签订主键id
                        map.put("iscollcon", objectMap.get("iscollcon"));//是否收款合同
                        map.put("relationproname", objectMap.get("relationprocodeEntity_proname"));//项目名称
                        map.put("subjectno", objectMap.get("subjectno"));//课题号

                        map.put("deposit", objectMap.get("deposit"));//开户银行
                        map.put("account", objectMap.get("account"));//银行账号
                        map.put("tin", objectMap.get("tin"));//纳税人识别号
                        //ponum订单号
                        map.put("ponum", objectMap.get("ponum"));//采购订单号
                        //handlerService.insert("gq_conaccount", map);
                        //绵阳合同是直接从签订进行录入，到台账，所以需要新建到台账数据
                        BigInteger accountid = null;
                        //0625 这块逻辑需要优化一下，如果查询台账为空，直接插入，不在根据是否是绵阳合同判断，如果不为空，就执行修改
                        if(CollectionUtils.isNotEmpty(list6)){
                            handlerService.update("gq_conaccount", map);
                        }else {
                            map.put("conid",objectMap.get("conid"));

                            accountid = (BigInteger) handlerService.insert("gq_conaccount", map);
                        }
                        //之前的逻辑，注释掉

//                        if(!"绵阳".equals(MapUtils.getString(objectMap,"signingplace"))){
//                            handlerService.update("gq_conaccount", map);
//                        }else{
////                            Map<String, Object> conapplicationMap = new HashMap<>();
////                            handlerService.addBizNum("conapplicationApp", "gq_conapplication", conapplicationMap);
//                            map.put("conid",objectMap.get("conid"));
//
//                            accountid = (BigInteger) handlerService.insert("gq_conaccount", map);
//                        }

                        //添加到合同信息表中
                        Map<String, Object> infomap = new HashMap<>();
                        infomap.put("concode", objectMap.get("concode"));//合同编号
                        infomap.put("conname", objectMap.get("conname"));//合同名称
                        infomap.put("typecode", objectMap.get("contracttype"));//合同类型
                        //infomap.put("constatus", objectMap.get("constatus"));//合同状态
                        infomap.put("constatus", "已签订");//合同状态
                        infomap.put("deptcode", objectMap.get("deptcode"));//合同部门
                        infomap.put("createuserdesc", objectMap.get("createuserdesc"));//创建人
                        infomap.put("performstatus", "未开始");//合同部门
                        infomap.put("relationprocode", objectMap.get("relationprocode"));//项目编号
                        if(CollectionUtils.isNotEmpty(list6)){
                            infomap.put("accountid", list6.get(0).get("id"));//合同台账主键id
                        }else{
                            infomap.put("accountid", accountid);//合同台账主键id
                        }

                        handlerService.insert("gq_coninfo", infomap);
                        //查询合同节点，插入到合同节点变更表
                        //String concode = (String) objectMap.get("concode");
                        String sql2 = "select * from gq_connode where concode = '" + concode + "'";
                        List<Map<String, Object>> list2 = handlerService.findBySql(sql2);
                        if (CollectionUtils.isNotEmpty(list2)) {
                            for (Map<String, Object> stringObjectMap : list2) {
                                stringObjectMap.put("nnodecode", stringObjectMap.get("nodecode"));
                                stringObjectMap.put("nnodename", stringObjectMap.get("nodename"));
                                stringObjectMap.put("nstarttime", stringObjectMap.get("starttime"));
                                stringObjectMap.put("nendtime", stringObjectMap.get("endtime"));
                                stringObjectMap.put("nreviewtime", stringObjectMap.get("reviewtime"));
                                stringObjectMap.put("nchestandard", stringObjectMap.get("chestandard"));
                                stringObjectMap.put("nispaynode", stringObjectMap.get("ispaynode"));
                                stringObjectMap.put("nconinfocode", stringObjectMap.get("coninfocode"));
                                stringObjectMap.put("nmilepostid", stringObjectMap.get("milepostid"));
                                stringObjectMap.put("nmainpayment", objectMap.get("mainpayment"));
                                stringObjectMap.put("nreceivingamounttax", objectMap.get("receivingamounttax"));
                                stringObjectMap.put("nreceivingamount", objectMap.get("receivingamount"));
                                stringObjectMap.put("invoicemoney", 0);
                                stringObjectMap.put("status", "未开始");
                                handlerService.insert("gq_connodenew", stringObjectMap);
                            }
                        }
                        //将上传的文件插入到合同台账的
                        fileSynUtilService.insertFiles(app, id, concode);
                    }
                    //如果是采购订单创建的合同，审批通过后，合同编号和名称同步到采购订单  同时要兼容，合同签订后，将供应商信息填写到外协订单中

                    handlerService.updateBySql("update gq_po set concode = '"+list.get(0).get("concode")+"',conname = '"+list.get(0).get("conname")+"',suppliername ='"+list.get(0).get("oppcompany")+"',suppliernum='"+list.get(0).get("supplierno")+"' where id = " +  list.get(0).get("poid")+" or conid ="+list.get(0).get("conid"));
                    //合同签订完，状态改为已签订
                    conchangeHandler.updateStatusByid(id, "已签订");
                    //conchangeHandler.updateStatus( (String) list.get(0).get("concode"),"已签订");
                    //流程归档
                    fileSynUtilService.processarc(app, id + "", "合同签订", (String) list.get(0).get("concode"), (String) list.get(0).get("conname"));

                    //判断，如果不是框架合同，gq_po显示
                    if("否".equals(list.get(0).get("isframecon"))){
                        handlerService.updateBySql("update gq_po set isshow ='是' where conid = "+list.get(0).get("conid"));
                    }
                }
                //将合同编号同步到外协订单里边
                //handlerService.updateBySql("update gq_po set concode = '"+list.get(0).get("concode")+"'  where conid = " +  list.get(0).get("conid"));

            }
        }
        return super.beforeExcuteFlow(app, id, flowNode, op);
    }
}
